package com.fulin.datastract.array;

/**
 * @Description TODO
 * @Author fulin16
 * @Date 2020/10/10 14:57
 **/

//Definition for singly-linked list.
class ListNode {
     int val;
     ListNode next;
     ListNode(int x) { val = x; }
}


class Solution {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(3);

        ListNode l2 = new ListNode(5);
        l2.next = new ListNode(6);
        l2.next.next = new ListNode(4);

        Solution solution = new Solution();
        solution.addTwoNumbers(l1,l2);
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode point = null;

        ListNode point1 = l1;
        ListNode point2 = l2;
        int val = 0;


        while(point1 != null || point2 != null){
            //不同时为null,则继续
            int val1 = point1 == null ? 0 : point1.val;
            int val2 = point2 == null ? 0 : point2.val;

            int temp = val1 + val2 + val;

            if(temp > 9){
                temp = temp - 10;
                val = 1;
            }else{
                val = 0;
            }

            ListNode node = new ListNode(temp);
            if(head == null){
                head = node;
                point = node;
            }else{
                point.next = node;
                point = point.next;
            }

            if(point1 != null){
                point1 = point1.next;
            }
            if(point2 != null){
                point2 = point2.next;
            }
        }
        if(val > 0){
            ListNode node = new ListNode(val);
            point.next = node;
        }

        return head;
    }
}